<template>
  <!-- 二次封装element form组件 -->
  <div>
    <el-form ref="ruleForm" :inline="true" :model="dataList" :label-position="labelPosition" :rules="rules">
      <div v-for="v of formData" :key="v.prop" class=" inline-block" :style="{ width: v.width }">
        <!-- 表单组件 -->
        <el-form-item v-if="['textarea', 'input', 'radio', 'button'].includes(v.type)" :ref="v.prop" :class="v.prop"
          :label="v.label" :prop="v.prop">
          <!-- 输入框组件/文本域组件 size="mini"-->
          <el-input  v-if="['textarea', 'input'].includes(v.type)" :maxlength="v.maxlength ? v.maxlength : ''"
            :show-word-limit="v.maxlength ? true : ''" :rows="v.rows" v-model.trim="dataList[v.prop]" :type="v.type"
            :placeholder="v.placeholder" :readonly="readonly"></el-input>
          <!-- 单选按钮控件 -->
          <el-radio-group v-if="['radio'].includes(v.type)" v-model="dataList[v.prop]">
            <el-radio label="1">11</el-radio>
            <el-radio label="2">22</el-radio>
          </el-radio-group>
          <!-- 按钮 -->
          <el-dropdown v-if="['button'].includes(v.type)">
            <el-button size="mini">
              性别<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" class="dropdown-menu">
              <el-dropdown-item>男</el-dropdown-item>
              <el-dropdown-item>女</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <!-- 上传组件 -->
        <div v-if="['upload'].includes(v.type)" class="upload-img">
          <!--        list-type="picture-card" -->
          <el-upload :ref="v.prop" :action="getFullPath('file/upload')"
            :file-list="dataList[v.showProp] ? dataList[v.showProp] : []"
            :headers="{ Authorization: $cookies.get('access_token_ygd') }" :data="{ fileType: 'img', isPublic: 1 }"
            :before-upload="
              (file, fileList) => {
                return beforeUpload(file);
              }
            " accept="image/jpeg,image/png" :limit="6" :on-success="
  (response, file, fileList) => {
    return handleAvatarSuccess(response, file, fileList, v);
  }
" :on-error="handleAvatarError" :on-change="
  (file, fileList) => {
    return handlerChange(file, fileList, v);
  }
">

            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-button>上传附件</el-button>
        </div>


      </div>
    </el-form>
  </div>
</template>
<script>
import configs from "@/configs";
export default {
  name: "FormNew",
  props: {
    // 表单渲染数据
    formData: {
      type: Array,
      default() {
        return [];
      },
    },
    // 表单数据
    dataInfo: {
      type: Object,
      default() {
        return {};
      },
    },
    // 表单校验规则
    rules: {
      type: Object,
      default() {
        return {};
      },
    },
    // label-position
    labelPosition: {
      type: String,
      default() {
        return "left";
      },
    },
    readonly: {
      type: Boolean,
      default() {
        return false;
      },
    },
  },
  computed: {},
  data() {
    return {
      dialogImageUrl: "", //图片放大
      dialogVisible: false, //显示放大的图片
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
        // {
        //   name: "food2.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
      dataList: JSON.parse(JSON.stringify(this.dataInfo)),
    };
  },
  watch: {
    dataInfo(newVal) {
      this.dataList = newVal;
      console.log("this.dataList", this.dataList);
    },
  },

  created() {
    this.showImg();
  },
  methods: {
    handlerChange(file, fileList, obj) {
      const el = this.$refs[obj.prop][0].$children[1].$el;

      if (fileList.length == 6) {
        el.style.display = "none";
        el.style.position = "absolute";
        el.style.right = "15px";
      }
    },
    // 处理图片回显
    showImg() {
      // return function (data, keys) {
      this.formData.forEach((v) => {
        if (v.type == "upload") {
          let arr = this.dataList[v.prop] ? this.dataList[v.prop] : [];
          let newArr = [];
          arr.forEach((v) => {
            newArr.push({
              name: v.name,
              url: v.url,
            });
            // }
          });
          // showProp绑定的字段来回显数据
          this.dataList[v.showProp] = newArr;
          // this.$nextTick(() => {
          //   // 超出6张隐藏上传控件
          //   // console.log('超出6张隐藏上传控件',this.dataList [v.prop]);
          //   if (this.dataList[v.prop] && this.dataList[v.prop].length >= 6) {
          //     const el = this.$refs[v.prop][0].$children[1].$el;
          //     el.style.display = "none";
          //   }
          // });
        }
      });
    },

    // 图片上传失败
    handleAvatarError(err) {
      console.log("err--图片上传失败", err);
      this.$message.error(JSON.parse(err.message).msg);
    },

    // 图片格式限制
    beforeUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log("isJPGorPNG", isJPGorPNG);
      if (!isJPGorPNG) {
        this.$message.error("请上传格式为jpg、png的图片");
      }
      if (!isLt2M) {
        this.$message.error("请上传大小不超过2M的图片");
      }
      return isJPGorPNG && isLt2M;
    },
    // 图片上传成功
    handleAvatarSuccess(response, file, fileList, obj) {
      console.log("图片上传...", this.dataList[obj.showProp]);
      if (response.code == 200) {
        this.dataList[obj.prop] ? "" : (this.dataList[obj.prop] = []); //后台返回null 处理成数组格式
        this.dataList[obj.prop].push(response.data.filename);
        // const arr = [];
        // this.dataList [obj.prop].forEach((v) => {
        //   // if (v instanceof Object) {
        //   //   arr.push(v.imagePath);
        //   // } else {
        //   //   arr.push(v);
        //   // }
        //   arr.push(v);
        // });
        // this.dataList [obj.prop] = arr;

        var random = Math.random().toFixed(13);
        var randomNumber = random * Math.pow(10, 13);

        console.log("fixedNumber", random, randomNumber);

        this.dataList[obj.showProp].push({
          name: "name",
          url: configs.STATIC_URL + "/" + response.data.filename,
          uid: randomNumber,
        });
        console.log("图片上传成功", this.dataList[obj.showProp]);
        // 超出6张隐藏上传控件
        if (this.dataList[obj.prop].length >= 6) {
          const el = this.$refs[obj.prop][0].$children[1].$el;
          el.style.display = "none";
        }
      } else {
        this.$message.error(response.msg);
      }
    },
    // 图片移除
    handleRemove(file, obj) {
      const el = this.$refs[obj.prop][0];

      const { showProp, prop } = obj;
      const ishowProp = this.dataList[showProp].findIndex((item) => {
        let b = file.response
          ? !item.url.includes(file.response.data.filename)
          : item.url !== file.url;
        return !b;
      });
      //  this.dataList [prop] = JSON.parse(JSON.stringify(this.dataList [prop]));
      this.dataList[showProp].splice(ishowProp, 1);
      const iProp = this.dataList[prop].findIndex((item) => {
        let b = file.response
          ? !item.includes(file.response.data.filename)
          : !file.url.includes(item);
        return !b;
      });
      // this.dataList [prop] = JSON.parse(JSON.stringify(this.dataList [prop]));
      this.dataList[prop].splice(iProp, 1);
      el.uploadFiles.splice(iProp, 1);
      // const { showProp, prop } = obj;
      // this.dataList [showProp] = this.dataList [showProp].filter((item) => {
      //   console.log("0000", file, item);
      //   let b = file.response
      //     ? !item.url.includes(file.response.data.filename)
      //     : item.url !== file.url;
      //   console.log("判断0", b);
      //   return b;
      // });

      // this.dataList [prop] = this.dataList [prop].filter((item) => {
      //   console.log("1111", file, item, !file.url.includes(item));
      //   let b = file.response
      //     ? !item.includes(file.response.data.filename)
      //     : !file.url.includes(item);

      //   console.log("判断1", b);

      //   return b;
      // });
      if (this.dataList[obj.prop].length < 6) {
        const el = this.$refs[obj.prop][0].$children[1].$el;
        el.style.display = "inline-block";
      }
      if (this.dataList[obj.prop].length <= 4) {
        console.log(1111, el.$children[1].$el);
        const ell = el.$children[1].$el;
        ell.style.position = "";
        ell.style.right = "";
      }
      console.log("ii", this.dataList[obj.prop].length);
    },
    // 图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //校验表单-提交按钮 外部调用方法
    $submitForm(cb) {
      console.log("校验表单-提交按钮", this.$refs.ruleForm);
      // return
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log("校验通过");
          cb && cb(true, JSON.parse(JSON.stringify(this.dataList)));
        } else {
          console.log("校验失败");
          cb && cb(false, JSON.parse(JSON.stringify(this.dataList)));
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {


  .el-form {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .el-form-item__label {
    color: #303133 !important;

  }

  .el-form-item {
    margin-right: 0px !important;
    display: flex;
  }

  .el-form-item__content {
    flex: 1;
  }

  .noDataUpload {
    font-size: 12px;

    .el-icon-plus {
      margin-top: 14px;
    }

    &:hover {
      color: #0170ef;

      .el-icon-plus {
        color: #0170ef;
        margin-top: 14px;
      }
    }
  }

  .el-dialog__wrapper {
    z-index: 2006 !important;
  }



  .el-dropdown {
    width: 100%;
  }

  .el-dropdown .el-button {
    width: 100% !important;
  }

}
</style>
<style>
/* 修改背景色以及border颜色*/
.dropdown-menu {
  min-width: 60px;
  text-align: center;
}
</style>
